<template>
    <div>
        <el-card>
            <el-table :data="records" row-key="id" v-loading="loading" border>
                <el-table-column prop="name" label="权限名称" min-width="200" align="center" />
                <el-table-column prop="acl" label="权限值" min-width="200" align="center" />
                <el-table-column label="操作" min-width="320" align="center" class="button-column">
                    <template #default="{ row }">
                        <el-button icon="Plus" v-show="row.level !== 3" @click="handleAdd(row)" v-has="'btn.addMenu'">
                            {{ row.level >= 2 ? '添加权限' : '添加菜单' }}
                        </el-button>
                        <el-button icon="Edit" v-show="row.level !== 0" @click="handleEdit(row)"
                            v-has="'btn.editMenu'">编辑</el-button>
                        <el-button type="danger" icon="Delete" v-show="row.level !== 0" @click="handleDelete(row)"
                            v-has="'btn.deleteMenu'">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>
        <el-dialog :title="isEdit ? '编辑权限' : '添加权限'" v-model="dialogVisible" :close-on-click-modal="false">
            <CreateOrEditACL v-if="dialogVisible" :is-edit="isEdit" :id="id" :level="level" @success="onSuccess">
            </CreateOrEditACL>
        </el-dialog>
    </div>
</template>

<script setup name="Menu">
import { ref, onMounted } from 'vue';
import { list, menuRemove } from '@/api/menu'
import CreateOrEditACL from './components/CreateOrEditACL.vue';
import { ElMessage, ElMessageBox } from 'element-plus';

// ---------- 查询 ----------
const loading = ref(false)
let records = ref([])

onMounted(() => submitForm())

const submitForm = async () => {
    loading.value = true
    const data = await list();
    if (data.code === 200) {
        records.value = data.data
    }
    loading.value = false
}

// ---------- 添加/编辑/删除 ----------
const isEdit = ref(false)
const dialogVisible = ref(false)
const id = ref()
const level = ref()

const handleAdd = (row) => {
    isEdit.value = false
    id.value = row.id
    level.value = row.level
    dialogVisible.value = true
}
const handleEdit = (row) => {
    isEdit.value = true
    id.value = row.id
    dialogVisible.value = true
}
const handleDelete = async (row) => {
    ElMessageBox.confirm(`确认删除权限【${row.name}】吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(async () => {
        const data = await menuRemove(row.id)
        if (data.code === 200) {
            ElMessage.success('删除成功');
            submitForm();
        } else {
            ElMessage.error('删除失败');
        }
    });
}
const onSuccess = () => {
    dialogVisible.value = false
    submitForm()
}
</script>

<style scoped lang="scss">
.el-card {
    min-width: 600px;
}
</style>
